package health_system.health_system.repository;



import health_system.health_system.entity.ChatMessage;
import health_system.health_system.entity.ChatRoom;
import health_system.health_system.entity.MessageReadStatus;
import health_system.health_system.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

@Repository
public interface MessageReadStatusRepository extends JpaRepository<MessageReadStatus, Long> {
    
    // Find read status of a message for a user
    Optional<MessageReadStatus> findByMessageAndUser(ChatMessage message, User user);
    
    // Find all read statuses for a message
    List<MessageReadStatus> findByMessage(ChatMessage message);
    
    // Check if all participants have read a message
    @Query("SELECT COUNT(rs) FROM MessageReadStatus rs " +
           "WHERE rs.message = :message AND rs.isRead = false")
    Long countUnreadStatusesForMessage(@Param("message") ChatMessage message);
    
    // Mark all messages as read in a chat room for a user
    @Modifying
    @Query("UPDATE MessageReadStatus rs SET rs.isRead = true, rs.readAt = CURRENT_TIMESTAMP " +
           "WHERE rs.message IN (SELECT m FROM ChatMessage m WHERE m.chatRoom = :chatRoom) " +
           "AND rs.user = :user AND rs.isRead = false")
    void markAllMessagesAsReadInRoom(@Param("chatRoom") ChatRoom chatRoom, @Param("user") User user);
    
    // Mark specific messages as read
    @Modifying
    @Query("UPDATE MessageReadStatus rs SET rs.isRead = true, rs.readAt = CURRENT_TIMESTAMP " +
           "WHERE rs.message.id IN :messageIds AND rs.user = :user")
    void markMessagesAsRead(@Param("messageIds") List<Long> messageIds, @Param("user") User user);
    
    // Find unread message statuses for a user
    @Query("SELECT rs FROM MessageReadStatus rs " +
           "WHERE rs.user = :user AND rs.isRead = false " +
           "ORDER BY rs.message.createdAt DESC")
    List<MessageReadStatus> findUnreadStatusesForUser(@Param("user") User user);
    
    // Count unread messages for a user across all chat rooms
    @Query("SELECT COUNT(rs) FROM MessageReadStatus rs " +
           "WHERE rs.user = :user AND rs.isRead = false")
    Long countUnreadMessagesForUser(@Param("user") User user);
    
    // Count unread messages for a user in a specific chat room
    @Query("SELECT COUNT(rs) FROM MessageReadStatus rs JOIN rs.message m " +
           "WHERE rs.user = :user AND m.chatRoom = :chatRoom AND rs.isRead = false")
    Long countUnreadMessagesInRoom(@Param("user") User user, @Param("chatRoom") ChatRoom chatRoom);
} 